import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue"
import User from "../views/User.vue"
import Cookies from "js-cookie";
import { hasPermissionToPath } from '@/utils/permission';

Vue.use(VueRouter)

const routes = [
  {
    path: "/login",
    component: () => import('@/views/Login.vue'),
    name: 'login'
  },
  {
    path: "/",
    component: () => import('@/views/Main.vue'),
    redirect:"/home",
    children: [
      {
        path: "/home",
        name: '首页',
        component: Home
      },
      {
        path: "/member",
        name: '会员管理',
        component: User
      },
      {
        path: "/employee",
        name: '员工管理',
        component: () => import('@/views/Employee.vue'),
      },
      {
        path: "/coach",
        name: '教练管理',
        component: () => import('@/views/Coach.vue'),
      },
      {
        path: "/course",
        name: '课程管理',
        component: () => import('@/views/Course.vue'),
      },
      {
        path: "/equipment",
        name: '器材管理',
        component: () => import('@/views/Equipment.vue'),
      },
      {
        path: "/notice",
        name: '公告管理',
        component: () => import('@/views/Notice.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  routes //缩写
})

router.beforeEach((to,from,next)=>{
  // 判断token
  const token=localStorage.getItem('token')
  if(!token && to.path!=='/login'){
    next('/login')
  }else if(token && to.path==='/login'){
    next('/home')
  }else if(token){
    // 已登录，检查权限
    if(hasPermissionToPath(to.path)){
      next()
    }else{
      // 没有权限，跳转到首页
      next('/home')
    }
  }else{
    next()
  }
})

export default router